package com.yunkazaixian.syntelecom.rabbitmq;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunkazaixian.syntelecom.rabbitmq.dto.MqMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Author:      gfl
 * Mail:        fuleiit@163.com
 * Date:        2023/10/15 17:36
 * Version:     1.0
 * Description:
 */
@Slf4j
@Component
public class MqMessageProducer {
    private static final ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private RabbitTemplate pointRabbitTemplate;

    /**
     * 发送消息
     * @param content
     */
    public void sendMessageToMQ(String content) {
        MqMessageDto dto = new MqMessageDto();
        dto.setContent(content);
        pointRabbitTemplate.convertAndSend(this.format(dto));
    }

    public void sendMessageToMQDxl(String content,String orderExchange,String orderRoutingKey,String expiration) {
        MqMessageDto dto = new MqMessageDto();
        dto.setContent(content);
        //发送消息  参数一:交换机 参数二:路由键(用来指定发送到哪个队列)
        pointRabbitTemplate.convertAndSend(orderExchange, orderRoutingKey, this.format(dto), message -> {
            // 设置消息过期时间 2小时过期    如果过期时间内还没有被消费 就会发送给死信队列 7200000
            message.getMessageProperties().setExpiration(expiration);
            message.getMessageProperties().setContentType("application/json");
            return message;
        });
        // pointRabbitTemplate.convertAndSend(this.format(dto));
    }

    public static String format(Object pojo) {
        try {
            return mapper.writeValueAsString(pojo);
        } catch (JsonProcessingException e) {
            log.error("JsonProcessingException, pojo = {}", pojo, e);
            return "{}";
        }
    }
}
